import os
from PIL import Image
from pathlib import Path
import tkinter as tk
from tkinter import filedialog, Entry, Button, StringVar
from tkinter import messagebox
def create_window(parent):

    if parent is None:
        root = tk.Tk()
    else:
        root = tk.Toplevel(parent)

    global offX, offY
    offX = 60
    offY = 50

    root.title("大图切割512")
    root.config(bg="grey")
    root.geometry("500x500+0+0")

    # 第一行：图片ID输入框
    entry_filename = StringVar()
    entry_path = Entry(root, textvariable=entry_filename)
    entry_path.place(x=offX + 100, y=offY - 27)
    tk.Label(root,text="图片前缀", bg='green').place(x=offX + 250, y=offY - 27)

    # 第二行：原始图片路径输入框
    entry_scale_org_path = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_org_path)
    entry_path1.place(x=offX + 100, y=offY + 20)
    tk.Label(root,text="请输入原始图片路径", bg='green').place(x=offX + 250, y=offY + 20)

    # 第三行：输出输入框
    entry_scale_target_path = StringVar()
    entry_path2 = Entry(root, textvariable=entry_scale_target_path)
    entry_path2.place(x=offX + 100, y=offY + 67)
    tk.Label(root, text="请输入输出目录路径", bg='green').place(x=offX + 250, y=offY + 67)

    # 第四行：图片参数
    def getImgSize():
        filename=entry_filename.get()
        width=0
        height=0
        if not filename:
            return ""
        img_path = os.path.join(entry_scale_org_path.get(), filename + ".png")
        if not os.path.isfile(img_path):
            return ""
        try:
            # 打开原始图片
            with Image.open(img_path) as img:
                width, height = img.size
        except Exception as e:
            print(f"处理图片时出错: {e}")
        img_size.set("原图尺寸：" + f"{width} x {height}")
    def getImgCount():
        global img_size
        filename=entry_filename.get()
        tile_size = 512
        cols=0
        rows=0
        if not filename:
            return ""
        img_path = os.path.join(entry_scale_org_path.get(), filename + ".png")
        if not os.path.isfile(img_path):
            return ""
        try:
            # 打开原始图片
            with Image.open(img_path) as img:
                width, height = img.size
                print(f"原始图片尺寸: {width}x{height}")

                # 计算行列数
                cols = width // tile_size
                rows = height // tile_size

                if width % tile_size != 0:
                    cols = cols + 1
                if height % tile_size != 0:
                    rows = rows + 1
        except Exception as e:
            print(f"处理图片时出错: {e}")
        img_count.set("拆分数量：" + f"{cols}列 x {rows}行 = {cols*rows}个")

    def getImgData():
        getImgSize()
        getImgCount()

    img_size = StringVar()
    img_size.set("原图尺寸：")
    tk.Label(root, textvariable=img_size, bg='green').place(x=offX + 50, y=offY + 110)
    # 绑定事件，在文件名输入框内容改变时更新显示
    entry_path.bind('<KeyRelease>', lambda event: getImgData())
    entry_path1.bind('<KeyRelease>', lambda event: getImgData())
    img_count = StringVar()
    img_count.set("拆分数量：")
    tk.Label(root, textvariable=img_count, bg='green').place(x=offX + 220, y=offY + 110)
    # 第五行：输出输入框
    button1 = Button(root, text="拆分图片", command=lambda: split_image_to_tiles(entry_filename.get(),entry_scale_org_path.get(),entry_scale_target_path.get()),
                     bg='skyblue')
    button1.place(x=offX + 150, y=offY +140)

    # 定义回调函数，当原始路径输入框内容变化时自动设置输出路径
    def update_target_path(*args):
        org_path = entry_scale_org_path.get()
        if org_path:
            # 自动设置输出路径为原始路径加/output
            target_path = org_path.rstrip('/\\') + '/output'
            entry_scale_target_path.set(target_path)
        else:
            # 如果原始路径为空，清空输出路径
            entry_scale_target_path.set('')

    # 绑定回调函数到原始路径变量
    entry_scale_org_path.trace('w', update_target_path)

    if parent is None:
        root.mainloop()


def split_image_to_tiles(filename,input_path, output_dir, tile_size=512):
    """
    将大图分割为多个512x512的小图
    
    参数:
        input_path (str): 输入图片路径
        output_dir (str): 输出目录
        tile_size (int): 每个小图的尺寸，默认为512
    """
    if not filename:
        messagebox.showerror("Error", "图片ID不能为空")
        return
    img_path=os.path.join(input_path,filename+".png")
    if not os.path.isfile(img_path):
        messagebox.showerror("Error","输入的图片路径不存在")
        return

    # 创建输出目录
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    
    try:
        # 打开原始图片
        with Image.open(img_path) as img:
            width, height = img.size
            print(f"原始图片尺寸: {width}x{height}")
            
            # 计算行列数
            cols = width // tile_size
            rows = height // tile_size
            
            if width % tile_size != 0:
                cols = cols + 1
            if height % tile_size != 0:
                rows = rows + 1
            print(f"将分割为 {cols}列 x {rows}行 = {cols*rows}个小图")
            
            
            # 分割图片
            for y in range(rows):
                for x in range(cols):
                    # 计算裁剪区域
                    left = x * tile_size
                    upper = y * tile_size
                    right = left + tile_size
                    lower = upper + tile_size
                    
                    # 裁剪并保存
                    tile = img.crop((left, upper, right, lower))
                    # output_path = os.path.join(output_dir, f"{filename}_{y}_{x}.png")
                    # tile.save(output_path)

                    # 如果图片有透明度通道，转换为RGB模式
                    if tile.mode == 'RGBA':
                        # 创建白色背景
                        background = Image.new('RGB', tile.size, (255, 255, 255))
                        # 将RGBA图片粘贴到白色背景上
                        background.paste(tile, mask=tile.split()[3])  # 使用alpha通道作为mask
                        tile = background
                    elif tile.mode != 'RGB':
                        # 确保图片是RGB模式
                        tile = tile.convert('RGB')

                    # 保存为JPG格式
                    output_path = os.path.join(output_dir, f"{filename}_{y}_{x}.jpg")
                    tile.save(output_path, "JPEG", quality=95)
                    
            print(f"成功分割并保存了 {cols*rows} 个 {tile_size}x{tile_size} 的小图到 {output_dir}")
    
    except Exception as e:
        print(f"处理图片时出错: {e}")

if __name__ == "__main__":
    create_window(None)
    # filename = input("图片前缀: ").strip()
    # input_image = input("请输入原始图片路径: ").strip()
    # output_directory = input("请输入输出目录路径: ").strip()
    #
    # if os.path.isfile(input_image):
    #     split_image_to_tiles(input_image, output_directory)
    # else:
    #     print("错误: 输入的图片路径不存在")